<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/21/021
 * Time: 10:06
 */

namespace Home\Controller;
use GatewayClient\Gateway;
use Think\Controller;
class ChatController extends Controller
{	


	private $commHeader = '/Public/images/chat-header.png';
	private $getUrl = "http://suibian.jinhengyy.com";
	protected function _initialize()
	{
		$mobile = I('mobile');
		if(ACTION_NAME == 'index'){
			$res = M('Register')->where(['register_name'=>$mobile])->find();
			$res['id'] = isset($res['id'])?$res['id']:"";
			if(!isset($_SESSION['msg']['id']) && $_SESSION['msg']['id'] == $res['id']){
				$_SESSION["msg"]=$res;
				define('UID', $_SESSION['msg']['id']);
			}else{
				$param["agent_tel"] = I("txt_Mobile");//邀请人手机号(上一级手机号)
				if($param["agent_tel"]=="")
				{
					$param["agent_id"]=0;//上一级id
					$param['upper_agent_id'] = 0;//上上一级id
					$param['upper_upper_agent_id'] = 0;//上上一级id
					$param['upper_agent_tel'] = 0;//上上一级手机号
					$param['upper_upper_agent_tel'] = 0;//上上上一级手机号
				}
				$param["register_name"] = $mobile;//用户名
				$param["tel"] = $mobile;//手机号
				$param["password"] = '123456';//密码
				$param["passwordTwo"] = '123456';//确认密码
				$param["verify"] = '123456';//验证码
				$param["create_time"]=date('y-m-d h:i:s',time());
				//dump($param["verify"]);die;
				$param["agent_tel"] = I("txt_Mobile");//邀请人手机号(上一级手机号)
				if ($param["register_name"] == "") {
					$this->error("用户名不能为空！");
				} 
				if ($param["tel"] == "") {
					$this->error("手机号不能为空！");
				}
				$param['password']=md5($param["password"]);
				$data = M("register");
				$re = $data->data($param)->add();
				$ress = M('Register')->where(['register_name'=>$mobile])->find();
				$_SESSION["msg"]=$ress;
				define('UID', $_SESSION['msg']['id']);
			}
		}else{
			define('UID', $_SESSION['msg']['id']);
		}
		/*if(isset($_SESSION['msg']['id'])){
			
		} else {
			$this->redirect('/index.php/Home/Login/login');
		}*/
	}
	//获取用户余额
	public function get_balance(){

		$mobile = $_SESSION['msg']['tel'];

		$balance = $this->curl_request($this->getUrl."/user/chatroom/get_balance?mobile=$mobile");

		return $balance;

	}

	//增减用户余额
	public function set_balance($mobile,$type,$money){

		$data['send_time'] = time();
		$data['password'] = md5(md5(substr($data['send_time'], 4)));
		$data['mobile'] = $mobile;
		$data['type'] = $type;
		$data['money'] = $money;

		$code = $this->curl_request($this->getUrl."/user/chatroom/set_balance",$data);

		return json_decode($code,true);

	}
	public function index() {
		$startTime = intval(strtotime($_SESSION['msg']['create_time']));
		$where['timeline'] = ['gt', $startTime];
		//获取群聊最新聊天记录
		$list = M('Chatlog')->where($where)->limit(20)->order('timeline desc')->select();
		$chatUser = M('Register');
		$history = [];
		foreach ($list as $k => $v) {
			$info = $chatUser->where(['id' => $v['fromid']])->find();
			$history[$k]['username'] = $info['nick_name'] ? $info['nick_name'] : '员工-'.$info['id'];
			$history[$k]['id'] = 'group';
			$history[$k]['avatar'] = $info['headimg'] ? $info['headimg'] : $this->commHeader;
			$history[$k]['timestamp'] = $v['timeline']*1000;
			$history[$k]['content'] = htmlspecialchars_decode($v['content']);
			$history[$k]['mine'] = $v['fromid'] == UID ? true : false;
			$history[$k]['type'] = "group";
		}
		$history = array_reverse($history);
		$this->assign('history', json_encode($history));

		//获取群名称
		$name = M('Group')->where(['id'=> 1])->getField('name');
		$this->assign('name', $name);
		//进入聊天界面绑定聊天
		$this->assign('uid', $_SESSION['msg']['id']);
		$this->assign('tel', $_SESSION['msg']['tel']);
		$info = M('Register')->where(['id'=>UID])->find();
		$this->assign('avatar', $info['headimg'] ? $info['headimg'] : $this->commHeader);
		$this->assign('register_name', $info['nick_name'] ? $info['nick_name'] : '员工-'.UID);

		$this->display();
	}

	//图片上传
	public function uploadImg() {
		$res = uploadImg();

		$returnMsg = [
			'code' => 0,
			'msg'  => '发送成功',
		];
		if ($res['status'] === 0) {
			$returnMsg = [
				'code' => 1,
				'msg'  => '发送失败'
			];
		} else {
			$returnMsg['data'] = ["src" => $res['src']];
			$this->ajaxReturn($returnMsg);
		}
	}

	//上传文件
	public function uploadFile() {
		$res = uploadFile();
		$returnMsg = [
			'code' => 0,
			'msg'  => '发送成功',
		];
		if ($res['status'] === 0) {
			$returnMsg = [
				'code' => 1,
				'msg'  => '发送失败'
			];
		} else {
			$returnMsg['data'] = ["src" => $res['src']];
			$this->ajaxReturn($returnMsg);
		}
	}

	/*
	 * 发红包
	 * 用户发送红包成功以后 红包就计入到内存中
	 * 24小时内无人领取红包 那么定时任务要把红包 返给用户
	 * */
	public function sendHongbao() {
		$total = floor(I('money', 0, 'floatval') * 100);  //金钱以分进行计算 防止误
		$num = I('num', 0, 'intval');            //红包个数
		$type = I('type', 0, 'intval');          //红包类型
		$remark = I('remark', '');               //留言
		$phone = I('phone', '');                 //制定人电话
		$receive_id = 0;                         //默认为0

		$hongbao = D('Hongbao');
		$register = M('Register');
		//校验数据
		if ($type == 1) {
			$balance = $this->get_balance();
			if(!(float)$balance){
				$this->ajaxReturn(V(0, '余额不足，请正确填写金额'));
			}
			//校验数据
			if($hongbao->create($_POST, 4) === false) {
				$this->ajaxReturn(V(0, $hongbao->getError()));
			}
		} else if ($type == 2) {
			$balance = $this->get_balance();
			if(!(float)$balance){
				$this->ajaxReturn(V(0, '余额不足，请正确填写金额'));
			}
			//校验数据
			if($hongbao->create($_POST, 5) === false) {
				$this->ajaxReturn(V(0, $hongbao->getError()));
			}
			$where['tel'] = $phone;
			$receive_id = $register->where($where)->getField('id');
			if (!$receive_id) {
				$this->ajaxReturn(V(0, '该手机号未注册'));
			}
			$num = 1;   //个人红包
		} else {
			$this->ajaxReturn(V(0, '参数错误'));
		}

		if ($remark === '') {
			$remark = '恭喜发财，大吉大利';
		}
		//插入红包
		$addArray = [
			'remark' => $remark,
			'money'  => $total,
			'num'    => $num,
			'register_id' => UID,
			'type' => $type,
			'add_time' => NOW_TIME,
			'receive_id' => $receive_id
		];

		M()->startTrans();
		$hongbao_id = $hongbao->add($addArray);
		if ($hongbao_id === false) {
			$this->ajaxReturn(V(0, '创建红包失败'));
		}

		//扣除用户余额度
		// $reduceMoney = $register->where('id='.UID)->setDec('commissions', $total/100);
		$setMoney = $this->set_balance($_SESSION['msg']['tel'],2,$total/100);
		$reduceMoney = $setMoney['error']==1 ?false : true;
		//组装批量插入数组
		$addTemp = [
			'hongbao_id' => $hongbao_id,
			'add_time'  => NOW_TIME,
		];

		$hongbaoArray = [];                      //所用的红包
		//群红包
		if ($type == 1) {
			$min = 1;                                //红包最小金额 0.01分
			$safe_total = 0;                         //防止波动太大
			$money = 0;                              //用户与获取的红包金额
			$tips = '群红包';                         //下文提示专用
			for ($i = 1; $i < $num; $i++) {
				$safe_total = ($total - ($num - $i)*$min)/($num-$i);     //以平均值作为安全上线可以使得红包值波动较小
				$money = (($this->randFloat()*($safe_total*100)+1)/100);       //以分进行计算的
				$money = floor($money);                                 //舍去分的小数点

				$addTemp['money'] = $money;
				array_push($hongbaoArray, $addTemp);

				$total = $total - $money;                               //一定为整数 钱精确到分
			}

			$addTemp['money'] = $total;
			array_push($hongbaoArray, $addTemp);                          //把剩余的余额作为最后一个红包 红包都是分
		} else { //个人红包
			$tips = $phone .'专属红包';
			$addTemp['money'] = $total;
			array_push($hongbaoArray, $addTemp);
		}

		$res = M('Hongbaotemp')->addAll($hongbaoArray);

		if ($res == false || $reduceMoney === false) {
			M()->rollback();
			$this->ajaxReturn(V(0, '创建红包失败'));
		} else {
			try{
				$str = '[div data-uid='.UID.' data-hongbaoid='.$hongbao_id.' class = hongbao]';
				$str .= 'img[/Public/images/sendhongbao.png]';
				$str .= '[div class = hongbao-right]';
				$str .= '[div class = hongbao-name]' . $remark . '[/div]';
				$str .= '[div class = hongbao-get]' . $tips . '[/div]';
				$str .= '[/div]';
				$str .= '[/div]';

				$chat_message = array(
					'type' => 'chatMessage',
					'data' => array(
						'username' => $_SESSION['msg']['tel'],
						'avatar'   => $this->commHeader,
						'id'       => 'group',
						'type'     => 'group',
						'content'  => $str,
						'timestamp'=> time()*1000,
					)
				);

				//写入聊天记录
				//聊天记录数组
				$param = [
					'fromid' => UID,
					'content' => $str,
					'timeline' => time(),
				];

				M('Chatlog')->add($param); //写入聊天记录
				$myMessage = $chat_message;
				$myMessage['data']['mine'] = true;

				//获取个人的token
				Gateway::sendToUid(UID, json_encode($myMessage));
				$client_id = Gateway::getClientIdByUid(UID);
				Gateway::sendToGroup('group', json_encode($chat_message), $client_id);


				M()->commit();
				$this->ajaxReturn(V(1, '创建成功', $hongbao_id));
			} catch (Exception $e) {
				M()->rollback();
				$this->ajaxReturn(V(0, '创建失败', $e->getMessage()));
			}
		}
	}

	//产生随机数
	function randFloat($min=0, $max=1){
		return $min + mt_rand()/mt_getrandmax() * ($max-$min);
	}

	//领取红包
	public function getHongbao() {
		//红包id
		$hongbao_id = I('hongbao_id', 0, 'intval');

		//查询红包类型 是制定还是群红包
		if(!$hongbao_id) {
			$this->ajaxReturn(V(0, '参数传递错误'));
		}

		$info = M('Hongbao')->where(['id'=>$hongbao_id])->find();
		if(!$info) {
			$this->ajaxReturn(V(0, '未查询到该红包'));
		}

		//红包24小时内未领取 就不能领取  $time 时间差
		$time = NOW_TIME - $info['add_time'];
		if($time > 24*3600) {
			$this->ajaxReturn(V(0, '红包已过期24小时不能领取'));
		}

		//如果红包指定人领取 过滤掉不能领取的人
		if($info['type'] == 2) {
			if($info['receive_id'] != UID) {
				$this->ajaxReturn(V(0, '专属红包您不能领取'));
			}
		}

		//每个人只能领取一次查询是否领取过红包
		$hongbaorecord = M('Hongbaorecord');
		if($hongbaorecord->where(['hongbao_id' => $hongbao_id,'register_id'=> UID])->count() > 0) {
			$this->ajaxReturn(V(0, '您已领取过该红包'));
		}

		//下面是符合领取条件的人 首先选择出来一个可以领取的红包 如果能选取到说明可以领取 如果选取不到那么就返回 开启事务隔离
		M()->startTrans();
		$hongbaotemp = M('Hongbaotemp');
		$personHongbao = $hongbaotemp->where(['hongbao_id' => $hongbao_id, 'is_get'  => 0, 'is_back' => 0])->find();
		if (!$personHongbao) {
			$this->ajaxReturn(V(0, '红包已被领完'));
		}

		//下面有红包 处理红包逻辑
		//修改该红包状态 标记已领取
		$res1 = $hongbaotemp->where(['id' => $personHongbao['id']])->setField('is_get', 1);

		//给领取人加钱
		// $res2 = M('Register')->where(['id' => UID])->setInc('commissions', $personHongbao['money']/100);
		$setMoney = $this->set_balance($_SESSION['msg']['tel'],1,$personHongbao['money']/100);
		$res2 = $setMoney['error']==1 ? false : true;
		//添加领取红包历史记录
		$data['register_id'] = UID;                     //谁领取了红包
		$data['money'] = $personHongbao['money'];   //以分为单位
		$data['add_time'] = NOW_TIME;
		$data['hongbao_id'] = $hongbao_id;              //红包id
		$res3 = $hongbaorecord->add($data);

		if($res1 !== false && $res2 !== false && $res3) {
			M()->commit();
			$this->ajaxReturn(V(1, '领取成功', ['data' => $data, 'hongbao' => $info]));
		} else {
			M()->rollback();
			$this->ajaxReturn(V(0, '领取失败'));
		}
	}

	//红包领取历史记录
	public function getHistory() {
		$page = ($page = I('page', 1, 'intval')) ? $page : 1;
		//字段 谁的红包  时间 金额
		$hongbaorecord = M('Hongbaorecord');
		$where['register_id'] = UID;
		$list = $hongbaorecord->where($where)->page($page)->limit(20)->select();

		$hongbao = M('Hongbao');
		$register = M('Register');
		foreach ($list as $k => $v) {
			$register_id = $hongbao->where(['id'=>$v['hongbao_id']])->getField('register_id');
			$name = $register->where(['id'=>$register_id])->getField('nick_name');
			$list[$k]['send_hongbao_name'] = $name == false ? '员工-'.$register_id : $name;
			$list[$k]['tel'] = $register->where(['id'=>$register_id])->getField('tel');
			$list[$k]['time_format'] = time_format($v['add_time']);
			$list[$k]['money'] = fen_to_yuan($v['money']);
		}

		if (!$list) {
			$list = [];
		}

		if (IS_AJAX) {
			$count = $hongbaorecord->where($where)->count();
			$this->ajaxReturn(V(1, '红包列表', ['list'=>$list, 'count'=>$count]));
		} else {
			$this->display('Chat/hongbao');
		}

	}

	//查看聊天历史记录
	public function getHistoryMessage() {
		//从这个时间开始 获得记录 聊天记录为50条
		$time = I('time', 0, 'intval');
		if($time == 0) {
			$this->ajaxReturn(V(0, '参数传递错误'));
		}

		$startTime = intval(strtotime($_SESSION['msg']['create_time']));
		$where['timeline'] = [['gt', $startTime], ['lt', $time]];

		$list = M('chatlog')->where($where)->limit(20)->order('timeline desc')->select();

		$register = M('Register');
		$history = [];
		foreach ($list as $k => $v) {
			$userInfo = $register->where(['id' => $v['fromid']])->find();
			$history[$k]['username'] = $userInfo['nick_name'] ? $userInfo['nick_name'] : '员工-'.$userInfo['id'];
			$history[$k]['avatar'] = $userInfo['headimg'] ? $userInfo['headimg']:$this->commHeader;
			$history[$k]['content'] = $v['content'];
			$history[$k]['timestamp'] = $v['timeline'];
			$history[$k]['mine'] = $v['fromid'] == UID;
			$history[$k]['cid'] = $v['fromid'];
		}
		$this->ajaxReturn(V(1, '历史记录', $history?$history:[]));
	}

	public function getMembers() {
		$register = M('Register');
		$list = $register->field('id, register_name, headimg, nick_name')->select();

		foreach ($list as $k=> $v) {
			$list[$k]['headimg'] = $v['headimg'] ? $v['headimg'] : $this->commHeader;
			$list[$k]['register_name'] = $v['nick_name'] ? $v['nick_name'] : '员工-'.$v['id'];
		}

		$this->ajaxReturn(V(1, '群成员', $list));
	}

	//修改群昵称
	public function setNickName() {
		$nickName = I('nickName', '');
		$length = mb_strlen($nickName);
		if ($length < 1 || $length > 10) {
			$this->ajaxReturn(V(0, '昵称为1到10个字符'));
		}

		if ($nickName != '') {
			if (M('Register')->where(['id'=>UID])->setField('nick_name', $nickName) !== false) {
				$this->ajaxReturn(V(1, '修改成功'));
			} else {
				$this->ajaxReturn(V(0, '修改失败'));
			}

		}
	}
	 //参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
	public function curl_request($url,$post='',$cookie='', $returnCookie=0){
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
			curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
			if($post) {
				curl_setopt($curl, CURLOPT_POST, 1);
				curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
			}
			if($cookie) {
				curl_setopt($curl, CURLOPT_COOKIE, $cookie);
			}
			curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
			curl_setopt($curl, CURLOPT_TIMEOUT, 10);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
			$data = curl_exec($curl);
			if (curl_errno($curl)) {
				return curl_error($curl);
			}
			curl_close($curl);
			if($returnCookie){
				list($header, $body) = explode("\r\n\r\n", $data, 2);
				preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
				$info['cookie']  = substr($matches[1][0], 1);
				$info['content'] = $body;
				return $info;
			}else{
				return $data;
			}
	}
}



